/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-05-13     lyh       the first version
 * 邮箱示例代码
 * 邮箱的管理方式：
 * 1.创建/初始化 rt_mb_create(name, size, flag)
 * 2.发送rt_mb_send(mb, value)
 * 3.接收rt_mb_recv(mb, value, timeout);
 * 4.删除/脱离  rt_mb_delete(mb)
 */

#include <rtthread.h>
#include <rtdevice.h>

#define THREAD_PRIORITY      10
#define THREAD_TIMESLICE     5
#define THREAD_SISLE     512
#define MAIL_SISLE     512
/* 邮箱控制块 */
static rt_mailbox_t mb;
static rt_thread_t mail_thread1 = RT_NULL;
static rt_thread_t mail_thread2 = RT_NULL;

static char mb_str1[] = "I'm a mail!";
static char mb_str2[] = "this is another mail!";
static char mb_str3[] = "over";

static void mail_thread1_entry(void * params)
{
    char *str;

    while (1)
    {
        rt_kprintf("thread1: try to recv a mail\n");

        /* 从邮箱中收取邮件 */
        if (rt_mb_recv(mb, (rt_uint32_t *) &str, RT_WAITING_FOREVER) == RT_EOK)
        {
            rt_kprintf("thread1: get a mail from mailbox, the content:%s\n", str);
            if (str == mb_str3)
                break;

            /* 延时 100ms */
            rt_thread_mdelay(100);
        }
    }
    /* 执行邮箱对象脱离 */
    rt_mb_detach(mb);
}

static void mail_thread2_entry(void * prams)
{
    rt_uint8_t count;

    count = 0;
    while (count < 10)
    {
        count++;
        if (count & 0x1)
        {
            /* 发送 mb_str1 地址到邮箱中 */
            rt_mb_send(mb, (rt_uint32_t) &mb_str1);
        }
        else
        {
            /* 发送 mb_str2 地址到邮箱中 */
            rt_mb_send(mb, (rt_uint32_t) &mb_str2);
        }

        /* 延时 200ms */
        rt_thread_mdelay(200);
    }

    /* 发送邮件告诉线程 1，线程 2 已经运行结束 */
    rt_mb_send(mb, (rt_uint32_t) &mb_str3);
}

int mail_sample(void)
{
    mb = rt_mb_create("mail-mb", MAIL_SISLE, RT_IPC_FLAG_FIFO);
    if (mb == RT_NULL)
    {
        rt_kprintf("init mail failed\n");
    }

    mail_thread1 = rt_thread_create("mail-thread1", mail_thread1_entry,
    RT_NULL, THREAD_SISLE, THREAD_PRIORITY, THREAD_TIMESLICE);

    mail_thread2 = rt_thread_create("mail-thread2", mail_thread2_entry,
    RT_NULL, THREAD_SISLE, THREAD_PRIORITY, THREAD_TIMESLICE);

    rt_thread_startup(mail_thread1);
    rt_thread_startup(mail_thread2);
    return 0;
}

MSH_CMD_EXPORT(mail_sample, mail_sample);
